package com.example.demo.service.imp;

import com.example.demo.config.DynamicDataSourceConfig;
import com.example.demo.config.ElasticSearchConfig;
import com.example.demo.entity.DataSource;
import com.example.demo.enums.Constants;
import com.example.demo.mapper.DatasourceMapper;
import com.example.demo.service.DatasourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DatasourceServiceImp implements DatasourceService {

    @Autowired
    private DatasourceMapper datasourceMapper;

    @Autowired
    private DynamicDataSourceConfig dynamicDataSourceConfig;

    @Autowired
    private ElasticSearchConfig elasticSearchConfig;

    @Override
    public List<DataSource> getAll() {
       List<DataSource> dataSources =  datasourceMapper.getAll();
        return dataSources;
    }

    @Override
    public boolean create(DataSource dataSource) {
        dataSource.init();
       int affectRow = datasourceMapper.insert(dataSource);
       if(affectRow>0){
           if(dataSource.getType().equals(Constants.DATASOURCE_TYPE_SQL.getCode())){
//           初始化一下动态数据源头
               dynamicDataSourceConfig.refresh();
           }
       }
       return affectRow>0;
    }

    @Override
    public boolean update(DataSource dataSource) {
        dataSource.initUpdate();
        int affectRow = datasourceMapper.updateById(dataSource);
        if(affectRow>0){
            if(dataSource.getType().equals(Constants.DATASOURCE_TYPE_SQL.getCode())){
                //           初始化一下动态数据源头
                dynamicDataSourceConfig.refresh();
            }
//            if(dataSource.getType().equals(Constants.DATASOURCE_TYPE_ES.getCode())){
//                elasticSearchConfig.refresh();
//            }
        }
        return affectRow >0;
    }

    @Override
    public boolean delete() {
        return false;
    }


    @Override
    public void loadDataSources() {
        List<DataSource> dataSources = this.getAll();
        for(DataSource dataSource:dataSources){

            String name = dataSource.getName();
            String url = dataSource.getUrl();
            String username = dataSource.getUsername();
            String password = dataSource.getPassword();
        }

    }
}
